package com.example.opengl.player.decoder

import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioTrack
import android.media.MediaCodec
import android.media.MediaFormat
import com.example.opengl.player.base.IExtractor
import com.example.opengl.player.extractor.AudioExtractor
import com.example.opengl.player.base.BaseDecoder
import java.nio.ByteBuffer

class AudioDecoder(path: String) : BaseDecoder(path) {
    /**采样率**/
    private var mSampleRate = -1

    /**声道通道数量**/
    private var mChannels = 1

    /**PCM采样位数**/
    private var mPCMEncodeBit = AudioFormat.ENCODING_PCM_16BIT

    /**音频播放器**/
    private var mAudioTrack: AudioTrack? = null

    /**音频数据缓存**/
    private var mAudioOutTempBuf: ShortArray? = null


    override fun doneDecode() {
        mAudioTrack?.stop()
        mAudioTrack?.release()
    }

    override fun render(outputBuffer: ByteBuffer, bufferInfo: MediaCodec.BufferInfo) {
        if (mAudioOutTempBuf!!.size < bufferInfo.size / 2) {
            mAudioOutTempBuf = ShortArray(bufferInfo.size / 2)
        }
        outputBuffer.position(0)
        outputBuffer.asShortBuffer().get(mAudioOutTempBuf,0,bufferInfo.size/2)
        mAudioTrack!!.write(mAudioOutTempBuf!!,0,bufferInfo.size/2)
    }

    override fun configCodec(codec: MediaCodec, format: MediaFormat): Boolean {
        codec.configure(format, null, null, 0)
        return true
    }

    override fun initSpecParams(format: MediaFormat) {
        try {
            mChannels = format.getInteger(MediaFormat.KEY_CHANNEL_COUNT)
            mSampleRate = format.getInteger(MediaFormat.KEY_SAMPLE_RATE)
            mPCMEncodeBit = if (format.containsKey(MediaFormat.KEY_PCM_ENCODING)) {
                format.getInteger(MediaFormat.KEY_PCM_ENCODING)
            } else {
                AudioFormat.ENCODING_PCM_16BIT
            }
        } catch (e: Exception) {

        }
    }

    override fun initRender(): Boolean {
        val channel = if (mChannels == 1) {
            //单声道
            AudioFormat.CHANNEL_OUT_MONO
        } else {
            AudioFormat.CHANNEL_OUT_STEREO
        }
        //获取音频最小缓冲区
        val minBufferSize = AudioTrack.getMinBufferSize(mSampleRate, channel, mPCMEncodeBit)
        mAudioOutTempBuf = ShortArray(minBufferSize / 2)
        mAudioTrack = AudioTrack(
            AudioManager.STREAM_MUSIC,
            mSampleRate,
            channel,
            mPCMEncodeBit,
            minBufferSize,
            AudioTrack.MODE_STREAM
        )
        mAudioTrack?.play()
        return true

    }

    override fun check(): Boolean = true

    override fun initExtractor(path: String): IExtractor = AudioExtractor(path)
}